package com.cheng.reggie.controller;

import com.cheng.reggie.common.R;
import com.cheng.reggie.util.UUIDUtils;
import jdk.nashorn.internal.runtime.URIUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    //读取配置文件中上传文件的目录
    @Value("${reggie.path}")
    private String baseDir;

    //springMVC文件上传要求
    //要求1:必须使用MultipartFile类型接收上传文件对象
    //要求2: MultipartFile类型参数名字必须与前端文件域表单元素name属性一样,如果不一致需要使用
    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //1.获取上传文件名
        String filename = file.getOriginalFilename();

        //.2获取上传文件扩展名
        String fileExcName = filename.substring(filename.lastIndexOf(".")); //.png/.jpg

        //创建唯一文件扩展名
        String newFileName  =  UUIDUtils.getUUID() + fileExcName;

        //3.将文件保存到F:\img\目录下面
        File dir = new File(baseDir);
        if (!dir.exists()){
            dir.mkdir();    //这里必须有F盘,这里判断没有则创建一个img目录
        }
        //进行保存
        file.transferTo(new File(baseDir + newFileName));

        //返回值
        return R.success(newFileName);
    }

    @RequestMapping("/download")
    public  void download(@RequestParam("name") String fileName, HttpServletResponse response) throws IOException {
        //输入流
        FileInputStream inputStream = new FileInputStream(baseDir + fileName);
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();

        IOUtils.copy(inputStream, outputStream);
    }
}
